# -*- coding: utf-8 -*-
# -----------------------------------------
# @Time       : 2018/6/18 9:37
# @Author     : dqz 
# @Email      : 1406990390@qq.com
# @File       : log.py
# @Software   : PyCharm
# -----------------------------------------
import logging
import os
import sys
import threading

from settings import LOG_DIR, DEBUG

if DEBUG:
    log_level = logging.DEBUG
else:
    log_level = logging.INFO


class Loggers(object):
    """
    日志处理累
    """
    _instance_lock = threading.Lock()

    def __init__(self, path=LOG_DIR, level=log_level):
        # if not os.path.exists(path):
        #     os.mknod(path)
        l_path = os.path.join(path, 'log.log')
        self.logger = logging.getLogger(l_path)
        self.logger.setLevel(level)

        formatter = logging.Formatter('[%(asctime)s] %(levelname)s %(message)s')

        fh = logging.FileHandler(l_path)
        fh.setLevel(level)
        fh.setFormatter(formatter)

        fs = logging.StreamHandler(sys.stdout)
        fs.setLevel(level)
        fs.setFormatter(formatter)

        e_formatter = logging.Formatter('[%(asctime)s] %(levelname)s %(filename)s [%(lineno)s %(message)s]')
        e_path = os.path.join(LOG_DIR, "error.log")
        eh = logging.FileHandler(e_path)
        eh.setLevel(logging.ERROR)
        eh.setFormatter(e_formatter)

        self.logger.addHandler(fh)
        self.logger.addHandler(fs)
        self.logger.addHandler(eh)

    def __new__(cls, path=LOG_DIR, level=logging.INFO):
        if not hasattr(cls, '_instance'):
            with Loggers._instance_lock:
                if not hasattr(cls, '_instance'):
                    Loggers._instance = super().__new__(cls)
        return Loggers._instance

    def debug(self, message):
        self.logger.debug(message)

    def info(self, message):
        self.logger.info(message)

    def warn(self, message):
        self.logger.warning(message)

    def critical(self, message):
        self.logger.critical(message)

    def error(self, message):
        self.logger.error(message)


log = Loggers()
